<?php
class FrontendAction extends Action
{
	public function __construct($context)
	{
		parent::__construct($context);
		$this->responseType = "XMLHttpRequest" == $context->server("HTTP_X_REQUESTED_WITH") ? "json" : "html";
		$viewClass = "Frontend" . ucfirst($this->responseType) . "View";
		$this->view = new $viewClass();
	}
	
	public function beforeExecute()
	{
		/**
		 * 检查用户cookie
		 */
		$this->context->cookie['user_id'] = Cookie::getCookie('user_id');
		if (0 == $this->context->cookie['user_id'])
		{
			/*
			 * 如果用户已经在discuz或者uchome中登录过，无须再登录
			 */
			$authUserId = ComsenzUserService::getAuthUserId();
			if ($authUserId)
			{
				$this->context->cookie['user_id'] = $authUserId;
				Cookie::setCookie(array(
					"name" => "user_id",
					"value" => $authUserId
				));
			}
		}
		if ($this->context->cookie['user_id'])
		{
			/**
			 * 设置当前用户角色
			 */
			$this->roles[] = "USER";
			/**
			 * 判断是否Owner
			 */
			if (($this->context->request("id") == $this->context->cookie['user_id']) || (null == $this->context->request("id") && null != $this->context->cookie['user_id']))
			{
				$this->roles[] = "OWNER";
			}
		}
		else
		{
			$this->roles[] = "ANONYMOUS";
		}
		/**
		 * 验证用户输入
		 */
		$validateInputResult = $this->_validateInput();
		if (count($validateInputResult))
		{
			$this->view->result["code"] = 406;
			$this->view->result["data"] = $validateInputResult;
		}
		/**
		 * 检查权限
		 */
		if (!$this->_checkPrivilege())
		{
			$this->view->result["code"] = 403;
		}
		/**
		 * 初始化View
		 */
		$layoutPrefix = in_array($this->context->uri["action"], array("Signin", "DoSignin", "Signup", "DoSignup", "DoSignout", "View")) ? '' : 'frame_';
		$layout = 'Do' == substr($this->context->uri['action'], 0, 2) || $this->view->result["code"] ? 'result' : 'frontpage';
		$this->view->layout = $layoutPrefix . $layout;
		if ($this->view->result["code"])
		{
			$this->view->render();
			exit;
		}
	}
}